var app = getApp();
//pages/order/downline.js
Page({
    data:{
        imageUrlFix: app.d.imageUrlFix,
        itemData:{},
        userId:0,
        paytype:'weixin',//0线下1微信
        remark:'',
        cartId:-1,
        goodsId:-1,
        buyNum: 0,
        addrId:0,//收货地址//测试--
        btnDisabled:false,
        productData:[],
        address:{},
       //total:0,  //合计
        totalAmount:0, //件数
        vprice:0,
        vid:0,
        addemt:1,
        vou:[],
        buyType: "buyCart",
        redirectUrl: '',
        isLack: -1,//是否存在超过库存的商品
        isShowToast: false, //toast默认不显示
        address_image: app.d.imageUrlFix + 'wechatShop/order_details_location.png',
        windowHeight:0,
        buyFn:null,
        hasShipping:false
    },
    onReady:function(){
      //获得dialog组件
      this.dialog = this.selectComponent("#dialog");
    },
    onLoad:function(options){
      var that=this;
      var uid = app.d.userId;
      this.setData({
        userId: uid,
        windowHeight: wx.getSystemInfoSync().windowHeight,
      });
      if (options.type=="buynow"){
        this.setData({
          buyType: options.type,
          goodsId:options.goodsId,
          buyNum: options.buynum,
          buyFn: that.loadGoodsDetail
        });
      }else{
        this.setData({
          cartId: options.cartId,
          buyFn: that.loadProductDetail
        });
      }
    },

    onShow: function(){
      this.callService();
    },
    
    callService:function(){
      var that = this;
      if(that.data.buyFn==null){
        setTimeout(function () { that.callService();},500);
      }else{
        this.querydefaultAddress(function () {
          that.data.buyFn();
        });
      }
    },

    loadGoodsDetail:function(){
      var that = this;
      var total = 0;
      that.setData({
        redirectUrl: '../address/user-address/user-address?def_type=1'
      })
      app.request("WxOrderController", "buyNow", {
        goodsId: that.data.goodsId,
        buyNum: this.data.buyNum,
        uid: that.data.userId,
        address: that.data.address
      }, function (data) {
        if (data.pro != null && data.pro.length > 0) {
          for (let i = 0; i < data.pro.length; i++) {
            total += data.pro[i].cart_num;
          }
          data["totalAmount"] = total;
        }
        that.setData({
          productData: data.pro,
          total: data.price,
          vprice: data.price,
          vou: data.vou,
          totalAmount: data.totalAmount,
          yun: data.yun,
          isLack: data.isLack,
          hasShipping: data.hasShipping
        });
        
        if (that.data.isLack == 1) {
          that.setData({
            count: 1500,
            toastText: "库存不足",
            btnDisabled: true,
            tips_icon: '/images/tips_icon3.png',
          });
          that.dialog.showDialog();
        } else {
          that.setData({
            btnDisabled: false,
          })
        }
      });
    },
    querydefaultAddress:function(callBackFn){
      var that = this;
      app.request("UserAddressService", "querydefaultAddress", {
        uid: that.data.userId,
      }, function (data) {
        if(data.adds.length > 0){
          var adds = data.adds;
          if (adds) {
            var addrId = adds[0].address_id;
            that.setData({
              addemt: 0,
              address: adds[0],
              addrId: addrId
            });
          }
        }else {
          that.setData({
            addemt: 1,
            address: {},
          });
        }
        callBackFn();
      });
    },
    loadProductDetail:function(){
        var that = this;
        var total = 0;
        that.setData({
            redirectUrl: '../address/user-address/user-address?def_type=1&cartId=' + that.data.cartId
        })
        app.request("WxOrderController", "buyCart", {
            cart_id: that.data.cartId,
            uid: that.data.userId,
            address: that.data.address
        }, function (data) {
            if (data.pro != null && data.pro.length > 0) {
              for (let i = 0; i < data.pro.length; i++) {
                total += data.pro[i].cart_num;
              }
              data["totalAmount"] = total;
            }
            that.setData({
                productData: data.pro,
                total: data.price,
                vprice: data.price,
                vou: data.vou,
                isLack: data.isLack,
                totalAmount: data.totalAmount,
                yun: data.yun,
                hasShipping: data.hasShipping
            });

            if(that.data.isLack == 1){
              that.setData({
                count: 1500,
                toastText: "库存不足",
                btnDisabled: true,
                tips_icon: '/images/tips_icon3.png',
              });
              that.dialog.showDialog();
            }else {
              that.setData({
                btnDisabled: false,
              })
            }
        });
    },

    remarkInput:function(e){
        this.setData({
            remark: e.detail.value,
        })
    },

    //选择优惠券
    getvou:function(e){
        var vid = e.currentTarget.dataset.id;
        var price = e.currentTarget.dataset.price;
        var zprice = this.data.vprice;
        var cprice = parseFloat(zprice) - parseFloat(price);
        this.setData({
            total: cprice,
            vid: vid
        })
    },

//微信支付
    createProductOrderByWX:function(e){
      this.setData({
          paytype: 'weixin',
      });
      this.createProductOrder();
        
    },

    //线下支付
    createProductOrderByXX:function(e){
        this.setData({
            paytype: 'cash',
        });
        wx.showToast({
            title: "线下支付开通中，敬请期待!",
            duration: 3000
        });
        return false;
        this.createProductOrder();
    },

    //确认订单
    createProductOrder:function(){
        this.setData({
            btnDisabled:false,
        })
        //创建订单
        var that = this;
        var address = that.data.address;
        if (address.full_address == null) {
          wx.showToast({
            title: '请先设置地址',
            icon: 'none',
            duration: 2000,
          })
          return;
        }
        if (!that.data.hasShipping){
          wx.showToast({
            title: '不支持该地区配送',
            icon: 'none',
            duration: 2000,
          })
          return;
        }
        app.request("WxOrderController", "createOrder", {
            uid: that.data.userId,
            cart_id: that.data.cartId,
            type: that.data.paytype,
            aid: address.address_id,//地址的id
            remark: that.data.remark,//用户备注
            price: that.data.total,//总价
            vid: that.data.vid,//优惠券ID
            yun: that.data.yun,
            buyFrom: that.data.buyType,
            goodsId: that.data.goodsId,
            buyNum: that.data.buyNum,
            address: that.data.address
        }, function (data) {
            //创建订单成功
            if (data.result.pay_type == 'cash') {
              wx.showToast({
                  title: "请自行联系商家进行发货!",
                  duration: 3000
              });
              return false;
            }
            if (data.result.pay_type == 'weixin') {
              //微信支付
              that.payOrder(data)
            }
        },function(data){
          that.setData({
            count: 1500,
            toastText: data.data.message,
          });
          that.showToast();
          return true;
        }
      );
    },

   /**
    * 微信支付
    */
    payOrder: function (order) {
      var that = this;
      var payType = "";
      if (order.result.pay_type == 'weixin'){
        payType = "wx";
      }
      wx.showLoading({
        title: '数据加载中',
      })
      app.request("WxPaymentController", "getPayParam", {
        openid: app.globalData.userInfo['openid'],
        orderId: order.result.order_id,
        orderAmount: order.price,
      },
        function (data) {
          wx.requestPayment({
            'timeStamp': data.timeStamp,
            'nonceStr': data.nonceStr,
            'package': data.package,
            'signType': data.signType,
            'paySign': data.paySign,
            'success': function (res) {

              app.request("WxPaymentController", "orderQuery", {
                orderId: order.result.order_id
              }, function (data) {
                wx.hideLoading();
                wx.showToast({
                  title: '操作成功',
                  duration: 2000,
                });
                app.request("WxOrderListService", "modOrderStatus", {
                  id: order.result.order_id,
                  type: 'confirmPay',
                  orderAmount: order.price,
                }, function (data) {
                  wx.redirectTo({
                    url: '../user/dingdanDetail?status=1&types=1&orderId=' + order.result.order_id,
                  })
                });

              }, function (data) {
                wx.hideLoading();
                wx.showToast({
                  title: "数据更新出错！",
                  duration: 2000,
                });
                wx.redirectTo({
                  url: '../user/dingdanDetail?status=0&types=1&orderId=' + order.result.order_id,
                })
                return false;
              }); 
            },
            'fail': function (res) {
              wx.showToast({
                title: "支付失败",
                duration: 2000,
              });
              wx.hideLoading();
              wx.redirectTo({
                url: '../user/dingdanDetail?status=0&types=1&orderId=' + order.result.order_id,
              })
            },
          })
        });
    },
});